package net.dgg.zz.api.production.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.dgg.common.tools.exception.ExceptionUtils;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.tmd.foundation.platform.treebook.entity.TreeBook;
import net.dgg.tmd.foundation.platform.treebook.service.TreeBookService;
import net.dgg.zz.api.production.service.ApiProductionService;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.*;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.OrderApiService;
import net.dgg.zz.production.excption.ProcessConfigException;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>@Title 生产部分对外接口controller</p>
 * <p>@Description 办理中相关</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author maoquanyi</p>
 * <p>@date 2018年08月13日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Controller
@RequestMapping("/api/zzsc/production")
@Api(description = "生产给IBOSS提供的接口")
public class ApiOutController extends DggBaseController {

    @Resource
    private ApiProductionService apiProductionService;
    @Autowired
    private OrderApiService apiservice;
    @Resource
    private TreeBookService treeBookService;



    //---------------  其他接口 -----------------------

    /**
    * <p>@Description 接口专用: 根据销售订单ID查询所有生产订单信息</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/19 0019 12:00 创建时间</p>
    * <p>@return</p>
    */
    @RequestMapping(value = "/query_product_order_by_order_id.do", method = RequestMethod.POST)
    @ResponseBody
    @NLog()
    public DggRestResponse queryProductOrderByOrderId(@RequestParam Long orderId) {
        try {
            String data = apiProductionService.queryProductOrderByOrderId(orderId);
            return this.getSuccessResponse(data);
        }  catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("0");
        }
    }



    /**
     * @Title:
     * @Description: 会员中心通过销售订单ID获取生产订单最新节点信息
     * @param:
     * @return:
     * @throw:
     * @author: wmj
     * @creat_date: 2019/2/27
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_scorder_latest_node_byorderid.do")
    @ApiOperation(value = "会员中心获取生产订单最新节点信息", notes = "会员中心获取生产订单最新节点信息接口", httpMethod = "POST")
    public DggRestResponse getScOrderLatestNodeByOrderId(@ApiParam(name = "orderId", value = "销售订单ID", required = true) @RequestParam Long orderId) {
        try {
            if (null != orderId) {
                Map params = new HashMap<>();
                params.put("orderId", orderId);
                Map scOrderMap = apiProductionService.getScOrderLatestNodeByOrderId(params);
                return this.getSuccessResponse(scOrderMap);
            } else {
                return this.getFailResponse("销售订单ID不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }


    /**
     * @Title:
     * @Description:  会员中心通过销售订单ID获取生产订单业务办理进度
     * @param:, method = RequestMethod.POST
     * @return:
     * @throw:
     * @author: wmj
     * @creat_date: 2019/2/27
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_scorder_bus_progress_byorderid.do")
    @ApiOperation(value = "会员中心获取生产订单业务办理进度", notes = "会员中心获取生产订单业务办理进度接口", httpMethod = "POST")
    public DggRestResponse getScOrderBusProgressByOrderId(@ApiParam(name = "orderId", value = "销售订单ID", required = true) @RequestParam Long orderId) {
        try {
            if (null != orderId) {
                Map params = new HashMap<>();
                params.put("orderId", orderId);
                List<List<Map<String, Object>>> scOrderListMap = apiProductionService.queryBusProgress(orderId);
                return this.getSuccessResponse(scOrderListMap);
            } else {
                return this.getFailResponse("销售订单ID不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }

    /**
     * @Title:
     * @Description: TODO 根据销售订单ID查询所有生产订单信息
     * @param:
     * @return:
     * @throw:
     * @author: sdx
     * @creat_date: 2019/8/27
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_zz_product_order_by_order_id.do", method = RequestMethod.POST)
    @ApiOperation(value = "根据销售订单ID查询所有生产订单信息", notes = "根据销售订单ID查询所有生产订单信息", httpMethod = "POST")
    public DggRestResponse getZzProductOrderByOrderId(@ApiParam(name = "orderId", value = "销售订单ID", required = true) @RequestParam Long orderId) {
        try {
            if (null != orderId) {
                Map params = new HashMap<>();
                params.put("orderId", orderId);
                List<Map<String, Object>> list = apiProductionService.getZzProductOrderByOrderId(params);
                return this.getSuccessResponse(list);
            } else {
                return this.getFailResponse("销售订单ID不能为空");
            }
        } catch (Exception e) {
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }

    /**
     * @Title:
     * @Description: TODO 根据生产订单ID查询当前节点，最新更新时间，办理人
     * @param:
     * @return:
     * @throw:
     * @author: sdx
     * @creat_date: 2019/8/26
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_product_order_by_id.do", method = RequestMethod.POST)
    @ApiOperation(value = "根据生产订单ID查询当前节点，最新更新时间，办理人", notes = "根据生产订单ID查询当前节点，最新更新时间，办理人", httpMethod = "POST")
    public DggRestResponse getProductOrderById(@Validated @RequestBody NodeOperateRecordCondition nodeOperateRecordCondition) {
        try {
            logger.info("查询节点记录开始---------》"+ JsonUtil.obj2Json(nodeOperateRecordCondition));
            if (null != nodeOperateRecordCondition) {
                Map params = new HashMap<>();
                params.put("scProductOrderId", nodeOperateRecordCondition.getScOrderId());
                List<Map<String, Object>> list = apiProductionService.getProductOrderById(params);
                return this.buildResponse(200,"请求成功！",list);
            } else {
                return this.getFailResponse("接收对象参数不能为空！");
            }
        } catch (Exception e) {
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }

    /**
     * @Title:
     * @Description: TODO 根据生产订单ID查询生产订单ID，任务ID，节点ID，任务名称，节点名称，最新更新时间，办理人,备注
     * @param:
     * @return:
     * @throw:
     * @author: sdx
     * @creat_date: 2019/8/26
     **/
    @ResponseBody
    @RequestMapping(value = "v1/get_product_node_by_id.do", method = RequestMethod.POST)
    @ApiOperation(value = "根据生产订单ID查询生产订单ID，任务ID，节点ID，任务名称，节点名称，最新更新时间，办理人,备注", notes = "根据生产订单ID查询生产订单ID，任务ID，节点ID，任务名称，节点名称，最新更新时间，办理人,备注", httpMethod = "POST")
    public DggRestResponse getProductNodeById(@Validated @RequestBody TaskOperateRecordPageCondition taskOperateRecordPageCondition) {
        try {
            logger.info("查询节点表开始---------》"+ JsonUtil.obj2Json(taskOperateRecordPageCondition));
            if (null != taskOperateRecordPageCondition) {
                Map params = new HashMap<>();
                params.put("scProductOrderId", taskOperateRecordPageCondition.getScOrderId());
                params.put("start", (taskOperateRecordPageCondition.getStart()-1) * taskOperateRecordPageCondition.getLimit());
                params.put("limit", taskOperateRecordPageCondition.getLimit());
                List<TaskOperateRecord> list = apiProductionService.getProductNodeById(params);
                PageList<TaskOperateRecord> pageList = new PageList<>();
                pageList.setRecords(list);
                pageList.setTotalCount(apiProductionService.count(params));
                pageList.setPageSize(taskOperateRecordPageCondition.getLimit());
                pageList.setCurrentPage(taskOperateRecordPageCondition.getStart());
                return this.buildResponse(200,"请求成功！",pageList);
            } else {
                return this.getFailResponse("接收对象参数不能为空！");
            }
        } catch (Exception e) {
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }




    /**
     * iBoss下单插入订单接口 审核通过调用
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/inset_order_all.do", method = RequestMethod.POST)
    public DggRestResponse insertOrderAll(@Validated @RequestBody QdsScOrderVo qdsScOrderVo){
        try{
            logger.info("打印销售订单信息==========================>");
            logger.info("销售主订单" + qdsScOrderVo.toString());
            if(StringUtils.isEmptyObj(qdsScOrderVo.getFlowerId())){
                return this.getFailResponse("请选择流程人员！");
            }
            TreeBook treeBook = treeBookService.getTreeBookByCode("ZZSC_SC_BUS_YT");
            if(StringUtils.isEmptyObj(treeBook)){
                return this.getFailResponse("资质生产未查询到数据字典");
            }
            if(StringUtils.isEmpty(treeBook.getExt1())){
                return this.getFailResponse("资质生产数据字典未配置可分单业态");
            }
            if(!treeBook.getExt1().contains(qdsScOrderVo.getOrderVo().getBusinessTypeNo())){
                return this.getFailResponse("资质生产暂不支持" + qdsScOrderVo.getOrderVo().getBusinessTypeName()  +"业态订单");
            }
            apiservice.allotScOrder(qdsScOrderVo);
            return this.getSuccessResponse("保存成功");
        }catch (ProcessConfigException e){
            logger.info(e.getMessage());
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (CommonExcption e){
            logger.info(e.getMessage());
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
            return this.getFailResponse("操作失败，请联系管理员！");
        }
    }

    /**
     *
     * 通过生产单id查询生产单的服务团队
     * @param scOrderId 销售订单编号
     * @return
     */
    @RequestMapping(value = "/getScOrderManagementTeam.do")
    @ResponseBody
    public DggRestResponse getScOrderManagementTeam(String scOrderId) {
        try {
            if(StringUtils.isEmpty(scOrderId)){
                return super.getFailResponse("生产单id为空！");
            }
            List<Map> userMap = apiservice.getScOrderManagementTeam(scOrderId);
            return super.getSuccessResponse(userMap);
        } catch (Exception e) {
            logger.error(e.toString());
            return this.getFailResponse("操作失败：" + e.getMessage());
        }
    }
}
